<template>
  <div style="height: 100%;">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="horizontal" >
          <a-row :gutter="8">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="queryParam.userName" placeholder="支持模糊查询"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="queryParam.fullName" placeholder="支持模糊查询"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="手机" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number v-model="queryParam.cellphone" placeholder="只能精确查找" style="width: 100%"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="所属组织" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    showSearch
                    v-model="queryParam.orgIds"
                    style="width: 100%"
                    :value="orgSelectTreeValue"
                    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="支持多选"
                    treeNodeFilterProp="title"
                    allowClear
                    multiple
                    treeDefaultExpandAll
                    :treeData="orgSelectTreeData"
                    @change="onChangeOrgSelectTree"
                    @search="onSearchOrgSelectTree"
                    @select="onSelectOrgSelectTree"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model="queryParam.status" placeholder="请选择" allowClear default-value="1">
                    <a-select-option value="0">禁用</a-select-option>
                    <a-select-option value="1">启用</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="用户类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model="queryParam.userTypes" mode="multiple" placeholder="支持多选" allowClear >
                    <a-select-option v-for="item in selectData.userType" :key="item.dictKey" :value="item.dictKey">{{ item.dictValue }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="() =>{this.findUserListBtn()}">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => {this.clearAll()}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <vxe-grid
        class="vxe-table-antd"
        resizable
        show-overflow
        ref="userListTable"
        stripe
        border
        highlight-hover-row
        highlight-current-row
        height="400"
        size="small"
        row-id="userId"
        :columns="tableColumn"
        :data="tableData"
        :loading="loading"
        :start-index="(tablePage.currentPage - 1) * tablePage.pageSize"
        :pager-config="tablePage"
        :radio-config="{ trigger: 'row'}"
        :edit-config="{trigger: 'click', mode: 'cell'}"
        @page-change="handlePageChange"
        @radio-change="radioChangeEvent">
      </vxe-grid>
      <a-modal
        :title="modalTitle"
        centered
        style="top: 20px;"
        width="85%"
        destroyOnClose
        v-model="visible"
        cancelText="关闭"
        okText="保存"
        @ok="saveUser"
        @cancel="cancelUser"
      >
        <user-form ref="userPage" :userInfo="selectRow" />
      </a-modal>
      <a-modal
        title="系统级权限授权"
        centered
        width="300"
        destroyOnClose
        v-model="sysPrivilegeVisible"
      >
        <template slot="footer">
          <a-button key="submit" type="primary" @click="closeSysPrivilege">
            确定
          </a-button>
        </template>
        <system-permission-form ref="userSystemPrivilegePage" :userInfo="selectRow" />
      </a-modal>
      <a-modal
        title="角色授权"
        centered
        style="top: 20px;"
        width="700px"
        destroyOnClose
        v-model="roleVisible"
        cancelText="关闭"
        okText="保存"
        @ok="saveRole"
      >
        <role-transfer-form ref="roleTransferPage" />
      </a-modal>
      <a-modal
        title="组织授权"
        centered
        style="top: 10px;"
        width="450px"
        destroyOnClose
        v-model="roleOrgVisible"
        @ok="saveOrg"
        cancelText="关闭"
        okText="保存"
      >
        <org-tree-form ref="orgTreePage" :userId="userId" />
      </a-modal>
      <a-modal
        title="资源授权"
        centered
        style="top: 10px;"
        width="450px"
        destroyOnClose
        v-model="roleRouterFuncVisible"
        @ok="saveRouterFunc"
        cancelText="关闭"
        okText="保存"
      >
        <router-func-tree-form ref="routerFuncTreePage" :userId="userId" />
      </a-modal>
    </a-card>
    <!-- fixed footer toolbar -->
    <footer-tool-bar>
      <a-button style="margin-left: 8px;" type="primary" icon="plus" @click="() =>{this.openSystemPrivilegePage()}">系统级权限分配</a-button>
      <a-button style="margin-left: 8px;" type="primary" icon="plus" @click="() =>{this.openRoleModel()}">角色分配</a-button>
      <a-tooltip placement="top" title="单独授权角色之外的功能权限">
        <a-button style="margin-left: 8px;" type="primary" icon="plus" @click="() =>{this.openUserRouterFuncModel()}">资源分配</a-button>
      </a-tooltip>
      <a-button style="margin-left: 8px;" type="primary" icon="plus" @click="() =>{this.openUserOrgModel()}">组织分配</a-button>
      <a-button style="margin-left: 8px" type="primary" icon="user-add" @click="() =>{this.openAddUser()}">创建用户</a-button>
      <a-button style="margin-left: 8px;" type="primary" icon="edit" @click="() =>{this.openEditUser()}">编辑用户</a-button>
      <a-button style="margin-left: 8px" type="danger" icon="user-delete" @click="() =>{this.deleteUser()}">删除</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import { getBatchDict, getOrgSelectTree,resetPassword, getUserList, editUserStatus, deleteUser, addUser, editUser, getUserRoleInfo, saveUserRole, saveUserOrg, saveUserRouterFunc  } from "@/services/system/api"
import FooterToolBar from '@/components/FooterToolbar'
import modal from 'ant-design-vue/es/modal'
import UserForm from '@/pages/system/form/UserForm'
import RoleTransferForm from '@/pages/system/form/RoleTransferForm'
import SystemPermissionForm from '@/pages/system/form/SystemPermissionForm'
import OrgTreeForm from '@/pages/system/form/OrgTreeForm'
import RouterFuncTreeForm from '@/pages/system/form/RouterFuncTreeForm'
import moment from 'moment'
export default {
  name: 'UserManager',
  components: {
    FooterToolBar,
    UserForm,
    SystemPermissionForm,
    RoleTransferForm,
    OrgTreeForm,
    RouterFuncTreeForm
  },
  data () {
    return {
      description: '用户信息管理',
      selectData: {},
      orgSelectTreeValue: undefined,
      orgSelectTreeData: [],
      visible: false,
      sysPrivilegeVisible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      form: null,
      mdl: {},
      // 角色授权
      roleVisible: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      loading: false,
      tablePage: {
        total: 0,
        pageNum: 1,
        currentPage: 1,
        pageSize: 20
      },
      tableColumn: [
        { type: 'radio', width: 40, fixed: 'left', align: 'center', slots: { header: () => { return [ <a-tooltip placement="top" title="取消选择"><a-icon type="stop" theme="twoTone" onClick={ this.clearRadioRowEevnt }/></a-tooltip> ] } } },
        { type: 'seq', width: 60, fixed: 'left', align: 'center', title: '序号' },
        { field: 'userName', title: '用户名', fixed: 'left', align: 'center', width: 150 },
        { field: 'fullName', title: '姓名', align: 'center', fixed: 'left', width: 150 },
        { field: 'userId', title: '用户Id', visible: false, align: 'center', width: 150 },
        { field: 'status', title: '状态', align: 'center', cellRender: { name: 'ASwitch', type: 'visible', events: { change: this.onStatusChange } }, width: 80 },
        { field: 'resetPassword', title: '重置密码', align: 'center', width: 80, slots: { default: ({ row }) => { return [ <a-tooltip placement="top" title="点击重置密码，重置后密码为：666666"><a-button type="danger" block onClick={ () => this.resetPasswordEevnt(row.userId) } >重置</a-button></a-tooltip> ] } } },
        { field: 'email', title: '电子邮箱', align: 'center', showOverflow: true, width: 150 },
        { field: 'cellphone', title: '手机', align: 'center', width: 100 },
        { field: 'idcard', title: '身份证', align: 'center', width: 150 },
        { field: 'userType', title: '用户类型key', visible: false, align: 'center', width: 150 },
        { field: 'userTypeName', title: '用户类型', align: 'center', width: 150 },
        { field: 'userIp', title: '使用用户ip', align: 'center', showOverflow: true, width: 200 },
        { field: 'orderNo', title: '顺序', align: 'center', width: 50 },
        { field: 'nikeName', title: '昵称', align: 'center', width: 150 },
        { field: 'sex', title: '性别', visible: false, align: 'center', width: 50 },
        { field: 'sexName', title: '性别', align: 'center', width: 50 },
        { field: 'birthday', title: '出生日期', align: 'center', width: 100 },
        { field: 'address', title: '地址', align: 'center', showOverflow: true, width: 200 },
        { field: 'officePhone', title: '办公室电话', align: 'center', width: 100 },
        { field: 'shortPhone', title: '短号', align: 'center', width: 60 },
        { field: 'orgId', title: '所属组织', visible: false, align: 'center', showOverflow: true, width: 150 },
        { field: 'orgName', title: '所属组织', align: 'center', showOverflow: true, width: 150 },
        { field: 'clientId', title: '所属应用', visible: false, align: 'center', showOverflow: true, width: 150 },
        { field: 'regdate', title: '创建日期', align: 'center', width: 80 },
        { field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 250 }
      ],
      tableData: [],
      selectRow: null,
      modalTitle: '操作',
      userId: null,
      roleOrgVisible: false,
      roleRouterFuncVisible: false
    }
  },
  created () {
    // 数据初始化
    // 数据字典初始化
    const params = {}
    params.dictFields = 'userType'
    this.$http.post(getBatchDict,params).then(res => {
      this.selectData = res.result
    })
    // 下拉组织树初始化
    this.$http.post(getOrgSelectTree,params).then(res => {
      this.orgSelectTreeData = res.result
    })
    // 初始化人员列表
    this.findUserList()
  },
  methods: {
    moment,
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    onChangeOrgSelectTree (value) {
      console.log(value)
      this.orgSelectTreeValue = value
    },
    onSearchOrgSelectTree () {
      console.log(...arguments)
    },
    onSelectOrgSelectTree () {
      console.log(...arguments)
    },
    radioChangeEvent ({ row }) {
      this.selectRow = row
      this.userId = row.userId
      console.log('单选事件')
    },
    clearRadioRowEevnt () {
      this.selectRow = null
      this.userId = null
      this.$refs.userListTable.clearRadioRow()
    },
    handlePageChange ({ currentPage, pageSize }) {
      this.tablePage.pageNum = currentPage
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.findUserList()
    },
    // 重置密码
    resetPasswordEevnt (userId) {
      const params = {}
      if (userId) {
        params.userId = userId
        this.$http.post(resetPassword,params).then(() => { modal.info({ title: '成功提示', content: '重置成功！密码为666666' }) }).catch(() => {})
      } else {
        modal.error({ title: '错误提示', content: '程序异常，未传入用户Id字段' })
      }
    },
    // 用户列表查询
    findUserListBtn () {
      this.tablePage.pageNum = 1
      this.tablePage.currentPage = 1
      this.findUserList()
    },
    findUserList () {
      this.loading = true
      const params = Object.assign(this.queryParam, this.tablePage)
      this.$http.post(getUserList,params).then((res) => {
        const data = res.result.list
        data.forEach((item) => {
          if (item.status === '1') {
            item.status = true
          } else {
            item.status = false
          }
        })
        this.tableData = data
        this.tablePage.total = res.result.total
        this.tablePage.pageNum = res.result.pageNum
        this.tablePage.currentPage = res.result.pageNum
        this.tablePage.pageSize = res.result.pageSize
        this.loading = false
        this.selectRow = null
        this.userId = null
      }).catch(() => {
        this.loading = false
      })
    },
    // 启用/禁用用户
    onStatusChange ({ row }, value) {
      const params = {}
      params.userId = row.userId
      params.status = '0'
      let text = '禁用'
      if (value) {
        text = '启用'
        params.status = '1'
      }
      setTimeout(() => {
        this.$http.post(editUserStatus,params).then(() => {
          modal.info({ title: '成功提示', content: text + '成功' })
        }).catch(() => {
          row.status = !value
        })
      }, 200)
    },
    openSystemPrivilegePage () {
      if (this.selectRow) {
        this.sysPrivilegeVisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要修改的数据' })
      }
    },
    openAddUser () {
      this.clearRadioRowEevnt()
      this.modalTitle = '新增用户信息'
      this.visible = true
    },
    openEditUser () {
      if (this.selectRow) {
        this.modalTitle = '修改用户信息'
        this.visible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要修改的数据' })
      }
    },
    closeSysPrivilege () {
      this.sysPrivilegeVisible = false
    },
    saveUser () {
      // 表单验证
      const { $refs: { userPage } } = this
      const userForm = new Promise((resolve, reject) => {
        userPage.form.validateFields((err, values) => {
          if (err) {
            reject(err)
            return
          }
          resolve(values)
        })
      })
      this.errors = []
      Promise.all([userForm]).then(values => {
        if (values && values.length > 0) {
          const user = values[0]
          if (user.birthday) {
            user.birthday = user['birthday'].format('YYYY-MM-DD')
          }
          if (user.userId) {
            setTimeout(() => {
              this.$http.post(editUser,user).then((res) => {
                modal.info({ title: '成功提示', content: '修改成功' })
                this.visible = false
                const data = [...this.tableData]
                if (res.result.status === '1') {
                  res.result.status = true
                } else {
                  res.result.status = false
                }
                data.forEach((item, index, arr) => {
                  if (item.userId === res.result.userId) {
                    arr.splice(index, 1, res.result)
                    return item
                  }
                })
                this.tableData = data
              }).catch(() => {
              })
            }, 200)
          } else {
            setTimeout(() => {
              this.$http.post(addUser,user).then((res) => {
                modal.info({ title: '成功提示', content: '新增成功' })
                this.visible = false
                this.queryParam.userName = res.result.userName
                this.findUserList()
              }).catch(() => {
              })
            }, 200)
          }
        }
      }).catch(() => {
        const errors = Object.assign({}, userPage.form.getFieldsError())
        const tmp = { ...errors }
        this.errorList(tmp)
      })
    },
    cancelUser () {
      const user = this.selectRow
      if (user) {
        const data = [...this.tableData]
        if (user.status === '1') {
          user.status = true
        } else {
          user.status = false
        }
        data.forEach((item, index, arr) => {
          if (item.userId === user.userId) {
            arr.splice(index, 1, user)
            return item
          }
        })
        this.tableData = data
      }
      this.visible = false
    },
    errorList (errors) {
      if (!errors || errors.length === 0) {
        return
      }
      this.errors = Object.keys(errors)
        .filter(key => errors[key])
        .map(key => ({
          key: key,
          message: errors[key][0]
        }))
    },
    deleteUser () {
      if (this.selectRow) {
        const params = {}
        params.userId = this.selectRow.userId
        setTimeout(() => {
          this.$http.post(deleteUser,params).then(() => {
            modal.info({ title: '成功提示', content: '删除用户成功' })
            this.findUserList()
          }).catch(() => {
          })
        }, 100)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要删除的数据' })
      }
    },
    openRoleModel () {
      if (this.selectRow) {
        const params = {}
        params.userId = this.selectRow.userId
        this.roleVisible = true
        setTimeout(() => {
          this.$http.post(getUserRoleInfo,params).then((res) => {
            this.$refs.roleTransferPage.setDataSource(res.result.roleList)
            this.$refs.roleTransferPage.setTargetKeys(res.result.targetKeys)
          }).catch(() => {
          })
        }, 50)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要授权的数据' })
      }
    },
    saveRole () {
      if (this.selectRow) {
        const checkedRoles = this.$refs.roleTransferPage.roleTargetKeys
        const userId = this.selectRow.userId
        const params = {}
        params.userId = userId
        params.userRoles = checkedRoles
        setTimeout(() => {
           this.$http.post(saveUserRole,params).then(() => {
            modal.info({ title: '成功提示', content: '授权成功' })
            this.roleVisible = false
          }).catch(() => {
          })
        }, 50)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要授权的数据' })
      }
    },
    openUserOrgModel () {
      // 打开组织授权页面
      if (this.userId) {
        this.roleOrgVisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的用户' })
      }
    },
    saveOrg () {
      if (this.userId) {
        const checkedObject = this.$refs.orgTreePage.checkedOrgKeys
        const checkedkeys = checkedObject.checked
        const params = {}
        params.userOrgIds = checkedkeys
        params.userId = this.userId
        setTimeout(() => {
           this.$http.post(saveUserOrg,params).then(() => {
            modal.info({ title: '成功提示', content: '授权成功' })
            this.roleOrgVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的用户' })
      }
    },
    openUserRouterFuncModel () {
      // 打开资源授权页面
      if (this.userId) {
        this.roleRouterFuncVisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的用户' })
      }
    },
    saveRouterFunc () {
      if (this.userId) {
        const checkedkeys = this.$refs.routerFuncTreePage.checkedKeys
        const params = {}
        params.objectIds = checkedkeys
        params.userId = this.userId
        setTimeout(() => {
           this.$http.post(saveUserRouterFunc,params).then(() => {
            modal.info({ title: '成功提示', content: '授权成功' })
            this.roleRouterFuncVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的用户' })
      }
    },
    clearAll () {
      this.queryParam = {}
      this.findUserList()
      setTimeout(() => {
        this.clearRadioRowEevnt()
        this.$refs.userListTable.clearSelection()
        this.$refs.userListTable.clearSelectReserve()
      }, 50)
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
